<?php

namespace Biz\service\esSearch;

use Biz\cache\brand\BrandScoreCache;
use Biz\model\wiki\Wiki;
use Doraemon\cache\EsUpdateCollector;
use Doraemon\cache\Queue;
use Doraemon\service\esSearch\Common;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;

class Brand
{
    public static function syncSave($data)
    {
        if (isset($data["data"]["id"]) && isset($data["data"]["store_status"]) && isset($data["type"])) {
            if ($data["type"] == Common::TYPE_ADD) {
                self::saveData($data["data"]);
            } else {
                if ($data["type"] == Common::TYPE_UPDATE) {
                    self::saveData($data["data"]);

                    $change_field = $data["change_field"] ?: [];
                    // 品牌权益
                    $isBrandRightChange = in_array('pack_type', $change_field);
                    if ($isBrandRightChange) {
                        // 更新用户
                        \Doraemon\cache\Queue::insertQueue('User/updateSolr', ['uid' => $data["data"]["uid"]],
                            Queue::QUEUE_ES_SYNC_COMMUNITY);
                        // 品牌批量更新 wiki
                        EsUpdateCollector::multiInsertBrandIdsForWikiBasic(array($data["data"]["id"]));

                        # 品牌权益更改 修改品牌内容上品牌信息 BrandChangePackType
                        self::_brandChangePackType($data["data"]["id"]);
                    }
                }
            }
        }
    }

    private static function _brandChangePackType($brandId)
    {
        try {
            $wikiInfos = Wiki::getInfosByBrandIds($brandId);

            $wikiIds = array();
            if (is_array($wikiInfos) && $wikiInfos) {
                foreach ($wikiInfos as $wikiInfo) {
                    if (isset($wikiInfo["id"]) && $wikiInfo["id"] > 0) {
                        array_push($wikiIds, $wikiInfo["id"]);
                    }
                }
            }

            $objIds = \Biz\model\wiki\ObjRelateWiki::getObjIdsByWikiIds($wikiIds);

            $noteIds = array();
            $articleIds = array();
            $blankIds = array();
            $guideIds = array();

            foreach ($objIds as $objId) {
                $type = IdParse::getType($objId);
                switch ($type) {
                    case BlockType::TYPE_PHOTO:
                    case BlockType::TYPE_ANSWER:
                        array_push($noteIds, $objId);
                        break;
                    case BlockType::TYPE_ARTICLE:
                        array_push($articleIds, $objId);
                        break;
                    case BlockType::TYPE_GUIDE:
                        array_push($guideIds, $objId);
                        break;
                    case BlockType::TYPE_BLANK:
                        array_push($blankIds, $objId);
                        break;
                }
            }

            if (is_array($noteIds) && $noteIds) {
                EsUpdateCollector::multiInsertIdsForNote($noteIds);
            }

            if (is_array($articleIds) && $articleIds) {
                EsUpdateCollector::multiInsertIdsForArticle($articleIds);
            }

            if (is_array($guideIds) && $guideIds) {
                EsUpdateCollector::multiInsertIdsForGuide($guideIds);
            }

            if (is_array($blankIds) && $blankIds) {
                EsUpdateCollector::multiInsertIdsForBlank($blankIds);
            }

            return true;
        } catch (\Exception $e) {
            Log::error($e->getMessage(), ['brand_id' => $brandId]);
            return false;
        }
    }

    public static function saveData($data)
    {
        $brandAliasArr = $data["brand_alias"] ? json_decode($data["brand_alias"]) : "";
        $brandAlias = "";

        if (is_array($brandAliasArr) && $brandAliasArr) {
            $brandAliasArr = array_values(array_filter($brandAliasArr));
            if (is_array($brandAliasArr) && $brandAliasArr) {
                $brandAlias = implode(" ", $brandAliasArr);
            }
        }

        $formatData = array(
            "brand_name" => $data["brand_name"],
            "en_brand_name" => $data["en_brand_name"],
            "brand_alias" => $brandAlias,
            "status" => $data["status"],
            "type" => $data["type"],
            "sort" => $data["sort"],
            "uid" => $data["uid"],
            "store_status" => $data["store_status"],
            "wiki_status" => $data["wiki_status"],
            "suggest_status" => $data["suggest_status"],
            "brand_type" => $data["brand_type"],
        );

        $updatedTime = $data["updated_time"] !== "0000-00-00 00:00:00" ? $data["updated_time"] : 0;
        $createdTime = $data["created_time"] !== "0000-00-00 00:00:00" ? $data["created_time"] : 0;

        $formatData["updated_time"] = strtotime($updatedTime);
        $formatData["created_time"] = strtotime($createdTime);

        // 品牌指数
        $brandScore = 0;
        if (intval($data["id"]) > 0) {
            $brandScore = BrandScoreCache::getBrandScore($data["id"]);
            $brandScore = empty($brandScore) ? 0 : $brandScore;
        }
        $formatData["brand_score"] = $brandScore;

        // 品牌权益
        $formatData['brand_pack_type'] = 0;
        $brandInfo = \Biz\model\brand\Brand::getInfo($data['id']);
        $formatData['brand_pack_type'] = $brandInfo["pack_type"];

        $formatData["brand_rights"] = "";
        $brandRights = \Biz\service\BrandRights\BrandRightsAllService::getBrandSearchSource($data["id"]);

        if (is_array($brandRights) && isset($brandRights[$data["id"]]) && $brandRights[$data["id"]]) {
            $formatData["brand_rights"] = implode(" ", $brandRights[$data["id"]]);
        }

        \Doraemon\service\es\EsStoreBrand::post($data["id"], $formatData);
    }

    public static function saveDataById($id)
    {
        $brandInfo = \Biz\model\brand\Brand::getInfo($id);
        self::saveData($brandInfo);
    }
}